#include "laurin-controller.h"
#include "../core/laurin-ip-network.h"


LaurinController::LaurinController()
{
	_options = LaurinControllerOptions();
	_devices = NULL;
	_clients = NULL;
}


LaurinController::~LaurinController()
{
	if(_devices)
	{
		_devices->stop(true);
		delete _devices;
	}

	if(_clients)
	{
		_clients->stop(true);
		delete _clients;
	}
}


void LaurinController::setOptions(LaurinControllerOptions options)
{
	if(options.areValid())
		_options = options;
}


LaurinControllerOptions LaurinController::getOptions() const
{
	return _options;
}


bool LaurinController::isRunning() const
{
	bool rs = false;
	if(_devices)
		rs = _devices->isWorking();

	if(!rs && _clients)
		return _clients->isWorking();

	return rs;
}


bool LaurinController::start()
{
	if(!_options.areValid() || isRunning())
		return false;

	bool okdevices = false;
	bool okclients = false;

	if(_options.operation_mode & LAURIN_DISCOVER_DEVICES_MODE)
	{
		if(!_devices)
		{
			_devices = new LaurinDiscoverDevicesModule(_options.monitor_device_name, _options.monitor_device_master_name);
			if(!_devices->isInitialized())
				return false;
		}

		_devices->setLocationEnable(_options.operation_mode & LAURIN_LOCATION_MODE);
		_devices->setMaxNumberOfFrame(_options.discover_max_frame);

		okdevices = true;
	}

	if(_options.operation_mode & LAURIN_DISCOVER_NETWORK_CLIENTS_MODE)
	{
		if(!_clients)
		{
			_clients = new LaurinDiscoverNetworkClientsModule(_options.network_device_name);
			if(!_clients->isInitialized())
				return false;
		}

		_clients->setFrameTimeout(_options.network_frame_timeout);

		okclients = true;
	}


	if(okdevices)
		_devices->start();

	if(okclients)
		_clients->start();


	return true;
}


void LaurinController::stop()
{

	if(_clients)
		_clients->stop(true);

	if(_devices)
		_devices->stop(true);

}


void LaurinController::fillModel(Laurin80211NetworksModel* model)
{
	if(_devices)
		model->fillStore(_devices->getNetworkSet());
}
